var app = getApp()
Page({
  data: {
    show: false,
    showModal: false,
    image: {
      download_url: ''
    },
    imgList: [],
    swiperList: [],
    allList: [],
  },
  onLoad() {
    this.getFromDB()
    this.fresh()
  },
  onReady() {
    this.setData({
      show: true
    })
  },
  getFromDB() {
    qq.showLoading({
      title: '加载中'
    })
    var that = this
    var skip = 0
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databasequery?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"love\").limit(20).skip(" + skip + ").orderBy(\"publish_time\", \"desc\").get()"
      },
      success(res) {
        //console.log(res)
        var list = res.data.data //数组中的内容需要在下面转成对象
        qq.hideLoading()
        if (list.length > 0) {
          that.getFileUrl(list)
        } else {
          qq.showToast({
            title: '已加载全部'
          })
        }
      }
    })
  },

  getFileUrl(list) {
    var that = this
    var idList = []
    for (var i = 0; i < list.length; i++) {
      var item = JSON.parse(list[i])

      var data = {
        fileid: item.imageid,
        max_age: 7200
      }
      idList[i] = data
    }
    //console.log(idList)
    qq.request({//请求拼装好的
      url: 'https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=' + app.globalData.access_token,
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "file_list": idList
      },
      success(res) {
        //console.log(res)
        that.setData({
          allList: res.data.file_list
        })
        that.fresh()
      }
    })
  },
  onPullDownRefresh() {
    this.setData({
      swiperList: [],
      imgList: [],
      allList: []
    })
    this.getFromDB()
  },
  onReachBottom() {
    this.getFromDB()
  },
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },
  showModal() {
    var that = this
    this.setData({
      showModal: !that.data.showModal
    })
  },
  chooseImage() {
    var that = this
    qq.chooseImage({
      count: 1, //默认9
      sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: (res) => {
        //console.log(res)
        that.zipImg(res.tempFilePaths[0])
      }
    });
  },
  zipImg(tempFilePath) {
    var that = this
    qq.getImageInfo({
      src: tempFilePath,
      success(res) {
        //console.log(res)
        var targetHeight = res.height
        var targetWidth = res.width
        var maxWidth = 500
        var maxHeight = 1200 //2100以内 按宽度1000，高度自适应压缩，
        //console.log(targetHeight, targetWidth)

        if (targetWidth > maxWidth || targetHeight > maxHeight) {
          if ((targetWidth / targetHeight) > (maxWidth / maxHeight)) {
            targetHeight = Math.round(maxWidth * (targetHeight / targetWidth));
            targetWidth = maxWidth;
            // //console.log(">") 顺序什么都不能改变，易错
          } else {
            targetWidth = Math.round(maxHeight * (targetWidth / targetHeight));
            targetHeight = maxHeight;
          }
        }
        //console.log(targetHeight, targetWidth)
        that.setData({
          targetWidth: targetWidth,
          targetHeight: targetHeight,
          canvasShow: true
        })
        setTimeout(function () {
          const ctx = qq.createCanvasContext('canvas');
          ctx.drawImage(tempFilePath, 0, 0, targetWidth, targetHeight);
          ctx.draw(false, function () {
            qq.canvasToTempFilePath({
              canvasId: ('canvas'),
              fileType: "jpg",
              quality: 0.5,
              destWidth: targetWidth,
              destHeight: targetHeight,
              success(res) {
                //console.log(res)
                const filePath = res.tempFilePath
                const cloudPath = 'love/' + app.globalData.openid + new Date().getTime() + filePath.match(/\.[^.]+?$/)[0]
                that.uploadFile(filePath, cloudPath)
                that.setData({
                  'image.download_url': filePath,
                  canvasShow: false
                })
              }
            })
          })
        }, 100)
      }
    })
  },
  uploadFile(filePath, cloudPath) { ///////////////////////////上传1张图片
    qq.showLoading({
      title: "上传中"
    })
    var that = this
    //console.log(filePath, cloudPath)
    var url = 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + app.globalData.access_token
    //console.log(url)
    qq.request({////////////////////////获取cos的url
      url,
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: {
        "env": app.globalData.myEnv,
        "path": cloudPath
      },
      method: "POST",
      success(res) {//////////////////////////通过cos上传
        //console.log(1, res)
        qq.uploadFile({
          url: res.data.url,
          filePath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data"//记得设置
          },
          formData: {
            key: cloudPath,
            "Signature": res.data.authorization,
            "x-cos-security-token": res.data.token,
            "x-cos-meta-fileid": res.data.cos_file_id
          },
          success(res2) { ////////////////////添加到数据库
            //console.log(res2)
            var data = {
              _openid: app.globalData.openid,
              imageid: res.data.file_id,
              publish_time: new Date().getTime()
            }
            that.addToDB(JSON.stringify(data))
            //console.log(data)
          }, fail(msg) {
            //console.log(msg)
          }
        })
        //console.log(res)
      }
    })
  },
  fresh() {
    this.setData({
      swiperList: this.data.allList.slice(0, 7),
      imgList: this.data.allList.slice(7)
    })
  },
  addToDB(data) {
    var that = this
    qq.request({
      url: 'https://api.weixin.qq.com/tcb/databaseadd?access_token=' + app.globalData.access_token, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json' // 默认值
      }, method: "post",
      data: {
        "env": app.globalData.myEnv,
        "query": "db.collection(\"love\").add({\
            data: "+ data + "\
        })"
      },
      success(res) {
        qq.hideLoading()
        qq.showToast({
          title: '上传成功！'
        })
        var image = Object.assign({}, that.data.image)
        that.data.allList = [image].concat(that.data.allList)
        that.setData({
          allList: that.data.allList
        })
        that.fresh()
      }
    })
  },
  viewImage(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.image.download_url],
      current: e.currentTarget.dataset.image.download_url
    });
  },

})